﻿using SqlSugar;
using System.Reflection;
using Models;
using Models.Entity;

namespace AuthServer.InitDatabaseExt
{
    public static class InitSqlSugarExt
    {
        /// <summary>
        /// 初始化SqlSugar
        /// </summary>
        /// <param name="builder"></param>
        public static void AddSqlSugar(this WebApplicationBuilder builder)
        {
            CustomConnectionConfig customConnectionConfig = new CustomConnectionConfig();
            builder.Configuration.Bind("ConnectionStrings", customConnectionConfig);

            //注册SqlSugar的服务
            builder.Services.AddScoped<ISqlSugarClient>(s =>
            {
                ConnectionConfig connection = new ConnectionConfig()
                {
                    ConnectionString = customConnectionConfig.ConnectionString,
                    DbType = DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute,
                    //SlaveConnectionConfigs = customConnectionConfig.SlaveConnectionConfigs.Select(c => new SlaveConnectionConfig() { ConnectionString = c.ConnectionString, HitRate = c.CustomHitRate }).ToList()
                };
                SqlSugarClient client = new SqlSugarClient(connection);


                // 自动初始化数据库中不存在的表（扫描 Models 命名空间）
                //InitDbTables(client);
                return client; 
            });

        }

        private static void InitDbTables(SqlSugarClient client)
        {
            string? targetNamespace = typeof(Sys_User).Namespace;
            if (string.IsNullOrEmpty(targetNamespace)) return;

            var modelAssembly = typeof(Sys_User).Assembly;

            var modelTypes = modelAssembly
                .GetTypes()
                .Where(t => t.IsClass && !t.IsAbstract && t.Namespace != null && t.Namespace.StartsWith(targetNamespace))
                .ToArray();

            client.CodeFirst.InitTables(modelTypes);
        }

    }
}
